<template>
  <div class="ImportXlsx">
    <!-- 按钮组件导入、导出、下载模板 -->
    <el-button icon="el-icon-download" type="success" plain @click="exportXlsx" size="mini" :disabled="disabled">导出Excel</el-button>
     <!-- :disabled="disabledImport" -->
    <el-button icon="el-icon-upload2" type="success" plain @click="importDialog=true" size="mini">导入Excel</el-button>
    <el-button icon="el-icon-download" type="success" plain @click="downloadTemplate" size="mini">下载模板</el-button>
    <!-- <el-button @click="ceshi">ceshi</el-button> -->
    <!-- <div>{{downloadData}}</div> -->
  <!-- 弹窗 -->
  <el-dialog
  title="导入"
  :visible.sync="importDialog"
  width="780px"
  :before-close="handleClose"
  >
    <!-- <el-upload
      class="upload-demo"
      action="https://jsonplaceholder.typicode.com/posts/"
      :on-change="handleChange"
      :file-list="fileList">
      <el-button size="small" type="primary">选择要导入的文件</el-button>
    </el-upload> -->
    <el-upload
      class="upload-demo"
      ref="upload"
      :headers='{Authorization:$store.state.user.token}'
      :action='importUrl'
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :on-success="handleSuccess"
      :on-error="handleError"
      :auto-upload="false">
      <!-- :on-error='onError' -->
      <!-- :on-change="handleChange" -->
      <!-- <el-dropdown-menu></el-dropdown-menu> -->
      <el-button slot="trigger" size="small" type="primary">选择要导入的文件</el-button>
      <!-- <el-button slot="trigger" size="small" type="primary">{{importUrl}}选择要导入的文件</el-button> -->
      <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">确认上传</el-button>
      <!-- <div slot="tip" class="el-upload__tip"></div> -->
    </el-upload>
    <!-- <el-progress :percentage="50"></el-progress> -->
  </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
// import { exprotXls,downTem } from '@/api/new20191221/exportXlsx'
import getToken from '@/utils/auth'
// import { exprotXls, importXls } from '@/api/new20191221/exportXlsx'
export default {
  name: 'ImportXlsx',
  // props:{
  //   // multipleSelection:{
  //   //   require:true
  //   // }
  //   // importUrl:{
  //   //   type: String,
  //   //   require: true
  //   // }
  // },
  props:['suoS', 'multipleSelection','importUrl','disabledImport','disabled'],
  data() {
    return {
      // 上传路径
      // importUrl: `/api/cb/flFactory/importXls`,
      // importUrl: `/api/cb/flFactory/importXls`,
        // 导入窗口开关
      importDialog: false,
      // importData: {
      //   // 上传数据
      fileList: [],
      disableExportData:false
      // 下载模板的数据
      // downloadData:null
      // }
    }
  },
  methods: {
    // disabledExport(){
    //   if (this.dataAttribute) {
    //     if (this.dataAttribute.length == 0) {
    //       this.disableExportData = true
    //     }else{
    //       this.disableExportData = false
    //     }
    //   }else{
    //       this.disableExportData = true
    //   }
    // },
    // onError(err,file,fileList){
    //   console.log(err,file,fileList,888);
      
    // },
    // 弹窗关闭
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(() => {
          done();
        }).catch(_ => {});
    },
    // 上传的方法
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    // handleChange(file, fileList){
    //   console.log(file, fileList);
    //   // if (file.raw) {
    //   //   this.$message({
    //   //     message
    //   //   }) 
    //   // }
    // },
    handleSuccess(res,file,fileList){
      // console.log(res,file,fileList,888);
      if (res.flag) {
        // 提醒
        this.$message({
          message:res.message,
          type:'success'
        })
        this.$emit('handleSuccessImport','导入成功')
      }else{    
        this.$alert(res.message, "导入失败：", {
          confirmButtonText: "确定",
          callback: action => {
            // this.$message({
            //   type: "warning",
            //   message: res.message
            // });
          }
        });
        // 提醒
        // this.$message({
        //   message:res.message,
        //   type:'warning'
        // })

      }
      // 清空数组
      this.fileList = []
      // 关闭窗口
      this.importDialog = false
    },
    handleError(res,file,fileList){
      console.log(res,file,fileList,'失败');
      
      // 清空数组
      // this.fileList = []
      // 关闭窗口
      // this.importDialog = false
      
    },
    // handleChange(file, fileList) {
    //   this.fileList = fileList.slice(-3);
    // },
    // // 进度条方法
    // format(percentage) {
    //   return percentage === 100 ? '满' : `${percentage}%`;
    // },
    // 导出方法
    async exportXlsx() {
      console.log('导出Xlsx',this.$parent.exprotXlsx,777);
      console.log(222);
      
      try {
        const { exprotXlsx } = this.$parent
        // console.log(exprotXlsx);
        // ----------------获取ids--------------------------------------------------------
        const suoSs = this.suoS
        let multipleSelections = this.multipleSelection
        console.log(multipleSelections,999);
        let ids = []
        for (let i = 0; i < multipleSelections.length; i++) {
          const element = multipleSelections[i];
          ids.push(element.id)
        }
        console.log(ids,'导出参数');
        console.log(suoSs,ids,'导出参数');
        const length = ids.length
        console.log(length,77555);
        
        let res = ''
        let idsq = 'ids'
        console.log();
        
        if (length) {
          console.log(ids,suoSs,'ids8');

          res = await exprotXlsx(ids,suoSs)
        }
        else{
          console.log('ids','idsq');
          res = await exprotXlsx('ids',suoSs)
        }
        // 判断是否有搜索条件
        // let searchBloon = false
        // for (const key in suoSs) {
        //   if (suoSs.hasOwnProperty(key)) {
        //     const element = suoSs[key];
        //     if (element !== '') {
        //       searchBloon = true
        //     }
        //   }
        // }
        // console.log(ids,'ids参数');
        // ----------------
        // -----------------判断条件---三种
        // let res = undefined
        // if (length) {
        //   console.log('ids');

        //   res = await exprotXlsx('',ids)
        // }
        // else if(searchBloon) {
        //   console.log('sou');
        //   res = await exprotXlsx(suoSs,'')
        // }
        // else{
        //   console.log('qita');

        //   res = await exprotXlsx('','')
        // }
        // ————————————————————————-----------------------------------------------------
        // const res = await exprotXlsx(ids,suoSs)
        // const res = await exprotXlsx()
        console.log(res,'导出结果');
        // let iconv = require('iconv-lite');
        // iconv.skipDecodeWarning = true;//忽略警告
        // let fileName = iconv.decode(res.filename, 'utf-8');
        // let fenge =fileName.split(';')[1]
        // fileName = fenge.split('=')[1]
        // console.log(fileName,'文件名');
        console.log(res,'导出结果');
        let fileName = decodeURI(
            res["filename"].split("=")[1]
        );

        // let blob = new Blob([res], {type: "application/vnd.ms-excel"});
        let blob = new Blob([res], {type: "application/vnd.ms-excel;charset=utf-8"});
        var downloadA = document.createElement('a')
        downloadA.download = fileName
        downloadA.style.display = 'none'
        downloadA.href=URL.createObjectURL(blob)
        document.body.appendChild(downloadA)
        downloadA.click()
        URL.revokeObjectURL(downloadA.href)
        document.body.removeChild(downloadA)
        // 提示
        this.$notify({
            title: '导出成功',
            message: fileName,
            type: 'success'
        });
      } catch (error) {
        console.log(error);
        this.$notify.error({
            title: "错误",
            message: "下载失败！"
        });
      }
    },
    // 模板下载
    async downloadTemplate(){
      console.log('模板下载',this.$parent.downloadFile ,6626);
      try {
        const { downloadFile } = this.$parent
        const res = await downloadFile()
        console.log(2222);
        
        // const res = await this.$parent.downloadFile()
        // let iconv = require('iconv-lite');
        // iconv.skipDecodeWarning = true;//忽略警告
        // let fileName = iconv.decode(res.filename, 'utf-8');
        // let fenge =fileName.split(';')[1]
        // fileName = fenge.split('=')[1]
        console.log(res,'导出结果');
        let fileName = decodeURI(
            res["filename"].split("=")[1]
        );
        // const blob  = new Blob([res],{type: 'application/vnd.ms-excel;charset=utf-8'})
        const blob  = new Blob([res],{type: 'application/vnd.ms-excel'})
        var downloadA = document.createElement('a')
        downloadA.download = fileName
        downloadA.style.display = 'none'
        downloadA.href=URL.createObjectURL(blob)
        document.body.appendChild(downloadA)
        downloadA.click()
        URL.revokeObjectURL(downloadA.href)
        document.body.removeChild(downloadA)
        // 提示
        this.$notify({
            title: '下载模板成功',
            message: fileName,
            type: 'success'
        });
      } catch (error) {
        console.log(error);
        this.$notify.error({
            title: "错误",
            message: "下载失败！"
        });
      }
    }
  },
  created(){
    // this.disabledExport()
  },
  wacth:{
    disabledImport(newValue){
      this.disabledImport = newValue
    }
  }
  // watch:{
  //   disabledExport(newValue){
  //     this.disabledExport = newValue
  //     this.disabledExport()
  //   }
  // }
}
</script>

<style lang="scss" scoped>
.ImportXlsx {
  display: inline-block;
}
</style>
